const axios = require("axios");
const md5 = require("md5");
const qs = require("qs");

const transParam = ($string, $lang) => {
  const $key = "kDvGucng8MW03HrTuVw7";
  const $data = {
    q: $string,
    from: "en",
    to: $lang,
    appid: "20220215001083495",
    salt: new Date().getTime(),
  };
  const $str = $data["appid"] + $data["q"] + $data["salt"] + $key;
  $data["sign"] = md5($str);
  return $data;
};
const transString = ($string, $lang) => {
  const $postdata = qs.stringify(transParam($string, $lang));
  return axios({
    url: `https://fanyi-api.baidu.com/api/trans/vip/translate?${$postdata}`,
    method: "GET",
  })
    .then((response) => {
      console.log(response.data);
      return response.data;
    })
    .catch(function (error) {
      console.log(error);
      return error;
    });
};

module.exports = transString;
